package com.golte.dataform.analysis.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

@Component
public class JwtUtil {

    public static final  String APP_SECRET = "eDjXmJ8JEkieNpOM";

    public static final long EXPIRE = 1000*60*120;


//    public String createToken(String data){
//        String token = Jwts.builder()
//                .setHeaderParam("typ", "JWT")
//                .setHeaderParam("alg", "HS256")
//                .setSubject("fx-token")
//                .setIssuedAt(new Date())
//                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
//                .claim("data", data)
//                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
//                .compact();
//        return token;
//    }

    public String createToken(Map data){
        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("fx-token")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .setClaims(data)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
        return token;
    }

    public boolean checkToken(String token){
        if(StringUtils.isEmpty(token))return false;
        try{
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public String getDataByToken(String token){
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return claims.get("data").toString();
    }

    public Claims parseJwt(String token) {
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        return claimsJws.getBody();
    }
}